/*
 * 文件名： WechatSdkPayPadServiceImpl.java
 * 
 * 工程名称: bis-service
 *
 * Gopay
 *
 * 创建日期： 2018年1月13日
 *
 * Copyright(C) 2018, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.service.bank.impl.scan;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.manager.bank.scan.ScanPayPabManager;
import com.gopay.bis.manager.bank.scan.SdkPayPabManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.PabConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.pab.agpay.PabTransResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayOrderResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayRefundQueryResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayRefundResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayStatusResMsg;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayServerNotifyMsg;
import com.gopay.common.domain.bank.wechat.sdk.res.SdkPayResMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayResMsg;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.FastJsonUtil;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.ScanPayInteractRemoteService;

/**
 * 
 *
 * @author 宣广海
 *
 * @version 
 *
 * @since 2018年1月13日
 */
public class WechatSdkPayPadServiceImpl implements ScanPayInteractRemoteService{
	/**
	 * 日志对象
	 */
	private static Logger logger = LoggerFactory.getLogger(WechatSdkPayPadServiceImpl.class);
	
	@Resource(name = "scanPayPabManager")
	private ScanPayPabManager scanPayPabManager;
	@Resource(name = "sdkPayPabManager")
	private SdkPayPabManager sdkPayPabManager;
	
	
	@Override
	public Result pay(BaseMessage msg) throws GopayException {
		logger.info("------------WechatSdkPayPadServiceImpl pay start-------------");
		long beginTime = System.currentTimeMillis();

		Result result = new Result(false);
		try {
			@SuppressWarnings("unchecked")
			PabTransResMsg<PayOrderResMsg> resMessage = (PabTransResMsg<PayOrderResMsg>) sdkPayPabManager.payment(msg);
			/**
			 * 定义返回对象
			 */
			SdkPayResMsg respMsg = new SdkPayResMsg();
			PayOrderResMsg payMsgBody = (PayOrderResMsg) resMessage.getBody();
			String jsapiJson=null;
			Map<String,String> jsmap=new HashMap<String,String>();
			if (StringUtils.equalsIgnoreCase(PabConstants.SUCCESS, resMessage.getErrcode())
					&& StringUtils.isNotBlank(payMsgBody.getAppId())) {
				BeanUtils.copyProperties(resMessage, respMsg);
				jsmap.put("appId", payMsgBody.getAppId());
				jsmap.put("partnerid", payMsgBody.getWxapp_partnerid());
				jsmap.put("prepayid", payMsgBody.getWxapp_prepayid());
				jsmap.put("package", payMsgBody.getWcpPackage());
				jsmap.put("nonceStr", payMsgBody.getNonceStr());
				jsmap.put("timeStamp", payMsgBody.getTimeStamp());							
				jsmap.put("sign", payMsgBody.getWxapp_sign());
				jsapiJson=FastJsonUtil.collectToString(jsmap);
				logger.info("------ return jsonStr:" + jsapiJson);
				respMsg.setToken_id(jsapiJson);
				result.setDefaultModel(respMsg);
				result.setSuccess(true);
			} else {
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E1159);
				result.setErrorMsg(resMessage.getMsg());
				result.setSuccess(false);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7025);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ WechatSdkPayPadServiceImpl pay end，耗时(ms):" + (endTime - beginTime));
		return result;	
	}

	@Override
	public Result orderQuery(BaseMessage msg) throws GopayException {
		logger.info("------------WechatSdkPayPadServiceImpl orderQuery start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result();
		try {
			@SuppressWarnings({ "unchecked" })
			PabTransResMsg<PayStatusResMsg> resMessage  = (PabTransResMsg<PayStatusResMsg> ) scanPayPabManager
					.orderQuery(msg);
			if (("".equals(resMessage.getBody().getTrade_amount())) || (null == resMessage.getBody().getTrade_amount())) {
				resMessage.setAmount(msg.getAmount());
			} else {
				resMessage.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(String.valueOf(resMessage.getBody().getTrade_amount()))));
			}
			result.setDefaultModel(resMessage);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ WechatSdkPayPadServiceImpl orderQuery end，耗时(ms):" + (endTime - beginTime));
		return result;
	}

	@Override
	public Result refund(BaseMessage msg) throws GopayException {

		logger.info("------------WechatSdkPayPadServiceImpl refund start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result(false);
		try {
			@SuppressWarnings("unchecked")
			PabTransResMsg<PayRefundResMsg> resMsg= (PabTransResMsg<PayRefundResMsg>) scanPayPabManager
					.refund(msg);
			if (resMsg != null) {
				if (PabConstants.SUCCESS.equals(resMsg.getErrcode())&&"0".equals(resMsg.getBody().getStatus())) {
					result.setDefaultModel(resMsg);
					result.setSuccess(true);
					// 接收成功
					result.setModel("falg", true);
				} else {
					result.setSuccess(false);
					result.setModel("falg", false);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
					result.setErrorMsg(resMsg.getMsg());
				}
			} else {
				result.setSuccess(false);
				result.setModel("falg", false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ WechatSdkPayPadServiceImpl refund end，耗时(ms):" + (endTime - beginTime));
		return result;	
	}

	@Override
	public Result refundQuery(BaseMessage msg) throws GopayException {

		logger.info("------------WechatSdkPayPadServiceImpl refundQuery start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result();
		try {
			@SuppressWarnings({ "unchecked" })
			PabTransResMsg<PayRefundQueryResMsg> resMessage  = (PabTransResMsg<PayRefundQueryResMsg> ) scanPayPabManager
					.refundOrderQuery(msg);
			resMessage.setAmount(msg.getAmount());
			result.setDefaultModel(resMessage);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ WechatSdkPayPadServiceImpl refundQuery end，耗时(ms):" + (endTime - beginTime));
		return result;
	
	}
	@Override
	public Result verify(BaseMessage msg) throws GopayException {
		Result result = new Result(false);
		try {
			ScanPayServerNotifyMsg message = (ScanPayServerNotifyMsg) msg;
			Boolean flag = (Boolean) scanPayPabManager.verify(message);
			result.setDefaultModel(flag);
			result.setSuccess(true);
			result.setModel("res", message);
			Map<String, String> param = new HashMap<String, String>();
			/**
			 * 验签成功
			 */
			if ((boolean) result.getDefaultModel()) {
				if (("0".equals(message.getPay_result()))) {
					param.put("orderId", message.getOrderId());
					param.put("amt", String.valueOf(message.getAmount()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					param.put("orderId", message.getOrderId());
					param.put("amt", String.valueOf(message.getAmount()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "验签失败");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	}

}
